﻿using System;
using System.Net;

namespace FRL.DebtChase.Common
{

	/// <summary>
	/// Declaration of ExtensionsForDates class
	/// </summary>
	public static class ExtensionsForDates
	{

		/////////////////////////////////////////////////////////////
		// Calculate date

		public static int CalcNearestValidDay( int iYear, int iMonth, int iDayOfMonthIn )
		{

			// Declare return variable
			int iFtmp = iDayOfMonthIn;

			// Reduce for days in month
			iFtmp = Math.Min( iFtmp, DateTime.DaysInMonth(iYear,iMonth) );

			// Return variable
			return iFtmp;

		}

		/////////////////////////////////////////////////////////////
		// Calculate date

		public static DateTime CalculateDate( int iYear, int iMonth, int iGenetive, DayOfWeek dayOfTheWeek )
		{

			// Declare return variable
			DateTime dtFtmp = new DateTime(iYear, iMonth, 1);

			// Loop through month
			while (true)
			{

				// If the day matches...
				if (dtFtmp.DayOfWeek == dayOfTheWeek)
				{

					// Decrement genetive
					iGenetive--;
					if (iGenetive == 0)
						break;

				}

				// Move on
				if (dtFtmp.Day == DateTime.DaysInMonth(iYear, iMonth))
					break;
				dtFtmp = dtFtmp.AddDays(1);

			} // while-loop

			// Return variable
			return dtFtmp;
 
		}

		/////////////////////////////////////////////////////////////
		// Count Nth weekday, eg, Third Wednessday

		public static int CountWeekDay(DateTime dt)
		{

			// Declare return variable
			int iFtmp = 0;

			// Loop through month
			DateTime dtTemp = new DateTime(dt.Year, dt.Month, 1);
			while (true)
			{

				// If day matches...
				if (dt.DayOfWeek == dtTemp.DayOfWeek)
					iFtmp++;

				// Move on
				if (dtTemp.Day == dt.Day)
					break;
				dtTemp = dtTemp.AddDays(1);

			} // while-loop

			// Return variable
			return iFtmp;

		}

		/////////////////////////////////////////////////////////////
		// Compare date part of timestamp

		public static bool IsSameDay(this DateTime dtA, DateTime dtB)
		{

			// Compare date component
			return (
				(dtA.Day == dtB.Day)
				&&
				(dtA.Month == dtB.Month)
				&&
				(dtA.Year == dtB.Year)
			);

		}

	}

}
